package com.xzy.demo.juc;

import java.util.concurrent.*;

/**
 * @ProductName: Hundsun HEP
 * @ProjectName: demo
 * @Package: com.xzy.demo.juc
 * @Description:
 * @Author: xiaozy37528
 * @CreateDate: 2021/8/9 19:54
 * @UpdateUser: xiaozy37528
 * @UpdateDate: 2021/8/9 19:54
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * <p>
 * Copyright © 2021 Hundsun Technologies Inc. All Rights Reserved
 **/
public class Test {

    public static ThreadPoolExecutor myThreadPoolExecutor() {
        // 核心线程数
        int corePoolSize = 3;

        // 最大线程数
        int maximumPoolSize = 6;

        // 非核心线程空闲时间、时间单位
        long keepAliveTime = 1000;
        TimeUnit unit = TimeUnit.MILLISECONDS;

        // 工作队列
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(3);

        // 拒绝策略：无空闲线程且工作队列已满时如何处理
        RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                System.out.println(System.currentTimeMillis() + " 线程池拒绝接收新任务：" + r.toString());
            }
        };

        // 线程工厂：用于创建线程
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                System.out.println(System.currentTimeMillis() + " 创建新线程：" + thread.getId());
                return thread;
            }
        };


        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, rejectedExecutionHandler);
    }

    public static void main(String[] arg) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(9);

        ThreadPoolExecutor myThreadPoolExecutor = myThreadPoolExecutor();
        for (int i = 0; i < 15; i++) {
            int finalI = i;
            myThreadPoolExecutor.submit(() -> {
                System.out.println(System.currentTimeMillis() + " 任务：" + finalI + " 使用线程：" + Thread.currentThread().getId());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
                System.out.println(System.currentTimeMillis() + " 任务：" + finalI + " 归还线程：" + Thread.currentThread().getId());
            });
        }

        countDownLatch.await();
        myThreadPoolExecutor.shutdown();

    }
}


